package com.gxdf.extendedcontrols.gxdfclient.components;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import com.gxdf.extendedcontrols.gxdfclient.data.Field;
import com.gxdf.extendedcontrols.gxdfclient.data.ValidationMessage;
import com.gxdf.extendedcontrols.gxdfclient.data.ValidationResult;
import com.gxdf.extendedcontrols.gxdfclient.data.ValidationType;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class GxdfSpinner extends GxdfField {
	
	ArrayList<String> values;
	
	
	ArrayAdapter<String> adapter;
	TextView lbl;
	Spinner spinner;
	

	public GxdfSpinner(Context context, Field f) {
		super(context, f);
		
		//values = options;
		this.setOrientation(VERTICAL);
		lbl = new TextView(context);
		lbl.setText(this.field.getLabelValue());
		spinner = new Spinner(context);
		spinner.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
		adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item,getField().getType().getPosValues());
		spinner.setAdapter(adapter);
		
		int numberOfItems = this.spinner.getAdapter().getCount();
		for(int i=0;i<numberOfItems;i++){
			String value = (String)spinner.getItemAtPosition(i);
			if(field.getValues().get(0).compareTo(value)==0)
				this.spinner.setSelection(i);
		}
		
		
		
	}

	@Override
	public void drawField() {		
		this.addView(this.lbl);
		this.addView(this.spinner);
		

		
	}

	@Override
	public String getValue() {		
		return this.spinner.getSelectedItem().toString();		
	}

	@Override
	public void saveValues() {
		List<String> newvalues = new ArrayList<String>();
		newvalues.add(0, spinner.getSelectedItem().toString());
		actualValues.clear();		
		actualValues=newvalues;		
	}

	@Override
	public boolean isModified() {
		return actualValues.equals(getField().getValues());
	}

	@Override
	public List<String> getActualValues() {		
		return this.actualValues;
	}

	@Override
	public boolean errorFormat() {
		boolean invalid = true;

		if (getField().getFormatValidation().isEmpty()) {
			invalid = false;
		} else {
			// TODO: Ejecutar regexp. Si falla return true else return false

			pattern = Pattern.compile(field.getFormatValidation());
			matcher = pattern.matcher(actualValues.get(0));
			invalid = matcher.matches();
		}

		return invalid;
	}

	@Override
	public boolean errorLength() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isFieldvalid() {
		// TODO Auto-generated method stub
		return isValid;
	}



}
